package com.example.springboot2.DB_Helper;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;


public class JDBCUtils {
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<Connection>();
    static {
        try {
            Class.forName("com.sqlserver.jdbc.Driver");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static Connection findConnection(){

        Connection connection = THREAD_LOCAL.get();
        if(connection ==null){
            try {
                connection= DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;database=JavaFramework;integratedSecurity=false;user=sa;password=1;");
            }catch (Exception e){
                e.printStackTrace();
            }
            THREAD_LOCAL.set(connection);
        }

        return connection;
    }
    /**
     * 关闭资源
     */
    public static void closeConnection(){

        Connection connection = THREAD_LOCAL.get();
        if(connection !=null){
            THREAD_LOCAL.remove();
            try {
                connection.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    public static List Populate(ResultSet rs,Class cc) throws SQLException, InstantiationException, IllegalAccessException{

        //结果集 中列的名称和类型的信息
        ResultSetMetaData rsm = rs.getMetaData();
        int colNumber = rsm.getColumnCount();
        List list = new ArrayList();
        Field[] fields = cc.getDeclaredFields();

        //遍历每条记录
        while(rs.next()){
            //实例化对象
            Object obj = cc.newInstance();
            //取出每一个字段进行赋值
            for(int i=1;i<=colNumber;i++){
                Object value = rs.getObject(i);
                //匹配实体类中对应的属性
                for(int j = 0;j<fields.length;j++){
                    Field f = fields[j];
                    if(f.getName().equals(rsm.getColumnName(i))){
                        boolean flag = f.isAccessible();
                        f.setAccessible(true);
                        f.set(obj, value);
                        f.setAccessible(flag);
                        break;
                    }
                }

            }
            list.add(obj);
        }
        return list;
    }



}

